from odoo import api, models, fields, _
import logging
import requests
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)


class SbSaleChangeLine(models.Model):
    _inherit = "sb.sale.change.line"

    def get_mes_token(self):
        return self.env["s.mes.login"].sudo().get_mes_token()

    def get_mes_url(self):
        """url"""
        url = self.env["s.api.config_parameter"].search([("s_key", "=", "mes.updateImsData")]).s_value
        return url

    def get_mes_doctype(self, param=None):
        """mes方法名"""
        if not param:
            return None
        else:
            mes_ = self.env["s.api.config_parameter"].search([("s_key", "=", param)])
            return mes_[0].s_value if mes_ else None

    def get_mes_enabled(self, param=None):
        """控制接口是否开启"""
        if not param:
            return None
        else:
            mes_ = self.env["s.api.config_parameter"].search([("s_key", "=", param)])
            return mes_[0].s_value if mes_ else None

    def action_hold(self):
        # 暂停
        res = super(SbSaleChangeLine, self).action_hold()
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            try:
                url = self.get_mes_url()
                self.with_delay().sent_mes_hold(url=url)
            except Exception as e:
                self.env["api.records"].create({
                    "api_route": url,
                    "result_json": e,
                    "state": "fail"
                })
        return res

    def sent_mes_hold(self, url):
        token = self.get_mes_token()
        doctype = self.get_mes_doctype(param="mes.lock")
        if not doctype: return True
        _logger.info("制造单暂停发送到mes {}-{}-{}".format(token, url, doctype))
        body = {"docType": doctype,"updateType": "UPDATE"}
        headers = {"Content-Type": "application/json","accessToken": token}
        mrp_production_ids = self.sale_order_id.mrp_production_ids
        all_productions_ids = mrp_production_ids
        for production in mrp_production_ids:
            all_productions_ids |= production._get_children()
        data = []
        reason = self.change_id.change_apply_id.note
        for mrp in all_productions_ids:
            data.append({
                "org_code": "0001",
                "lock_reason": reason,
                "mo_code": mrp.name,
                "hold_by": self.env.user.name
            })
        body["data"] = data
        res = requests.post(url, json=body, headers=headers)
        result = res.json()
        if result.get("resultCode") != "0000":
            raise ValidationError("Body: {}, Result: {}".format(body, str(result.get("resultMsg"))))
        self.env["api.records"].create({
            "api_route": url,
            "result_json": result,
            "state": "success"
        })

    def action_cancel_hold(self):
        # 取消暂停
        res = super(SbSaleChangeLine, self).action_cancel_hold()
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            try:
                url = self.get_mes_url()
                self.with_delay().sent_mes_cancel_hold(url=url)
            except Exception as e:
                self.env["api.records"].create({
                    "api_route": url,
                    "result_json": e,
                    "state": "fail"
                })
        return res

    def sent_mes_cancel_hold(self, url):
        token = self.get_mes_token()
        doctype = self.get_mes_doctype(param="mes.unlock")
        if not doctype:
            return True
        _logger.info("制造单取消暂停发送到mes {}-{}-{}".format(token, url, doctype))
        body = {"docType": doctype,"updateType": "UPDATE"}
        headers = {"Content-Type": "application/json","accessToken": token}
        mrp_production_ids = self.sale_order_id.mrp_production_ids
        all_productions_ids = mrp_production_ids
        for production in mrp_production_ids:
            all_productions_ids |= production._get_children()
        data = []
        reason = self.change_id.change_apply_id.note
        for mrp in all_productions_ids:
            data.append({
                "org_code": "0001",
                "unlock_reason": reason,
                "mo_code": mrp.name,
                "unlock_by": self.env.user.name
            })
        body["data"] = data
        res = requests.post(url, json=body, headers=headers)
        result = res.json()
        if result.get("resultCode") != "0000":
            raise ValidationError("Body: {}, Result: {}".format(body, str(result.get("resultMsg"))))
        self.env["api.records"].create({
            "api_route": url,
            "result_json": result,
            "state": "success"
        })
